# encoding: utf-8
import requests


from config import DMS_URL

class DMSOperator:

    # 根据文件id获得json文件
    def get_jsonfile(self, file_id: str):
        headers = {
            "accept": "text/plain"
        }
        print(file_id)
        # file_id = file_id
        url = f"{DMS_URL}/sysIntegrating/aiIntegrating/fileContent/analysisWord/"+file_id
        # print(url)
        retry_num = 1
        while retry_num <= 10:
            try:
                response = requests.get(url, headers=headers)
                break
            except Exception as e:
                print(f"An unexpected error occurred: {e}")
                retry_num += 1
        if retry_num > 10:
            print("Max retry reached.")
        # print("-"*25)
        # print(response.text)
        # print("-" * 25)
        return response.json()["data"]

    # 根据文件路径获得pdf的json文件
    def get_pdf2jsonfile(self, filerealpath: str):
        headers = {
            "accept": "text/plain"
        }
        print(filerealpath)
        # file_id = file_id
        url = f"{DMS_URL}/sysIntegrating/aiIntegrating/fileContent/analysisPdf/"+filerealpath
        # print(url)
        retry_num = 1
        while retry_num <= 10:
            try:
                response = requests.get(url, headers=headers)
                break
            except Exception as e:
                print(f"An unexpected error occurred: {e}")
                retry_num += 1
        if retry_num > 10:
            print("Max retry reached.")
        # print("-"*25)
        # print(response.text)
        # print("-" * 25)
        return response.json()["data"]

    # 根据文件路径获得pdf文件
    def get_docx2pdf(self, filerealpath: str):
        headers = {
            "accept": "text/plain"
        }
        print(filerealpath)
        # file_id = file_id
        url = f"{DMS_URL}/sysIntegrating/aiIntegrating/fileContent/wordToPdf/"+filerealpath
        # print(url)
        retry_num = 1
        while retry_num <= 10:
            try:
                response = requests.get(url, headers=headers)
                break
            except Exception as e:
                print(f"An unexpected error occurred: {e}")
                retry_num += 1
        if retry_num > 10:
            print("Max retry reached.")
        # print("-"*25)
        # print(response.text)
        # print("-" * 25)
        return response.json()["data"]


    # 获得纯文本
    def get_textfile(self, file_path: str):
        headers = {
            "accept": "text/plain"
        }
        print(file_path)
        # file_id = file_id
        url = f"{DMS_URL}/sysIntegrating/aiIntegrating/fileContent/readFileText/" + file_path
        # print(url)
        retry_num = 1
        while retry_num <= 10:
            try:
                response = requests.get(url, headers=headers)
                break
            except Exception as e:
                print(f"An unexpected error occurred: {e}")
                retry_num += 1
        if retry_num > 10:
            print("Max retry reached.")
        # print("-"*25)
        # print(response.text)
        # print("-" * 25)
        return response.json()["data"]

    # excel 转 md
    def get_excel2md(self, file_path: str):
        headers = {
            "accept": "text/plain"
        }
        url = f"{DMS_URL}/sysIntegrating/aiIntegrating/fileContent/excelToMarkdown/" + file_path
        retry_num = 1
        while retry_num <= 10:
            try:
                response = requests.get(url, headers=headers)
                break
            except Exception as e:
                print(f"An unexpected error occurred: {e}")
                retry_num += 1
        if retry_num > 10:
            print("Max retry reached.")
        return response.json()["data"]

    # 第一版编辑文件
    def post_edit_file(self, edit_file: dict):
        headers = {
            "accept": "text/plain",
            "Content-Type": "application/json-patch+json"
        }
        retry_num = 1
        while retry_num <= 10:
            try:
                response = requests.post(f"{DMS_URL}/sysIntegrating/aiIntegrating/fileContent/editWord",
                                         headers=headers, json=edit_file)
                break
            except Exception as e:
                print(f"An unexpected error occurred: {e}")
                retry_num += 1
        if retry_num > 10:
            print("Max retry reached.")
        print(response.text)
        return response.json()
    # # 下载文件
    # def get_file(self, dms_filepath, dms_filename):
    #     headers = {
    #         "accept": "text/plain"
    #     }
    #     params = {
    #         "filePath": dms_filepath,
    #         "fileName": dms_filename
    #     }
    #     response = requests.get(f"{DMS_URL}/sysIntegrating/aiIntegrating/fileContent/download", headers=headers,
    #                              params=params)
    #     with open(f"../../文档/下载文档/{dms_filename}", "wb") as f:
    #         f.write(response.content)
    #     return response.status_code



    # 上传两个文件id，对比文件差异
    def get_diff_jsonfile(self, file_id: str):
        headers = {
            "accept": "text/plain"
        }
        params = {
            "SourceFileId": file_id,
            # "CompareFileId": file_id2
        }
        retry_num = 1
        while retry_num <= 10:
            try:
                response = requests.get(f"{DMS_URL}/sysIntegrating/aiIntegrating/fileContent/compareWordParagraph",
                                        headers=headers,
                                        params=params)
                break
            except Exception as e:
                print(f"An unexpected error occurred: {e}")
                retry_num += 1
        if retry_num > 10:
            print("Max retry reached.")
        # print(response.text)
        return response.json()


    # 获取两个文件id的表格文件差异
    def get_diff_jsonfile_table(self, file_id: str):
        headers = {
            "accept": "text/plain"
        }
        params = {
            "SourceFileId": file_id,
            # "CompareFileId": file_id2
        }
        retry_num = 1
        while retry_num <= 10:
            try:
                response = requests.get(f"{DMS_URL}/sysIntegrating/aiIntegrating/fileContent/compareWord",
                                        headers=headers,
                                        params=params)
                break
            except Exception as e:
                print(f"An unexpected error occurred: {e}")
                retry_num += 1
        if retry_num > 10:
            print("Max retry reached.")
        # print(response.text)
        return response.json()


    # 上传文件id，转换文件类型
    def get_fileconversion(self, file_id: str, file_type_num: int):
        headers = {
            "accept": "text/plain"
        }
        json_data = {
            "fileId": file_id,
            "TargetFileType": file_type_num
        }
        retry_num = 1
        while retry_num <= 10:
            try:
                response = requests.post(f"{DMS_URL}/sysIntegrating/aiIntegrating/fileContent/fileConversion",
                                         headers=headers,
                                         json=json_data)
                break
            except Exception as e:
                print(f"An unexpected error occurred: {e}")
                retry_num += 1
        if retry_num > 10:
            print("Max retry reached.")
        if '"code":500' in response.text:
            return None
        else:
            return response.text

    # 回调dms系统
    def post_exchange_info(self, exchange_info: dict):
        # exchange_info = {
        #     "functionType": 1,
        #     "taskType": 1,
        #     "taskDocumentType": 1,
        #     "executionType": 1,
        #     "isSuccess": True,
        #     "dmsTaskId": "string",
        #     "docId": file_id,
        #     "fileId": "string",
        #     "resultFilePath": "string",
        #     "aiTaskId": task.id
        # }
        headers = {
            "accept": "text/plain",
        }
        retry_num = 1
        while retry_num <= 10:
            try:
                response = requests.post(f"{DMS_URL}/integrate/aiIntegrating/fileHandleResult", headers=headers,
                                         json=exchange_info)
                break
            except Exception as e:
                print(f"An unexpected error occurred: {e}")
                retry_num += 1
        if retry_num > 10:
            print("Max retry reached.")
        return response.text

    # 操作文件（批注，添加背景色）
    def post_operate_file(self, operate_file: dict):
        headers = {
            "accept": "text/plain",
            "Content-Type": "application/json-patch+json"
        }
        retry_num = 1
        while retry_num <= 10:
            try:
                response = requests.post(f"{DMS_URL}/sysIntegrating/aiIntegrating/fileContent/operationWord",
                                         headers=headers,
                                         json=operate_file)
                break
            except Exception as e:
                print(f"An unexpected error occurred: {e}")
                retry_num += 1
        if retry_num > 10:
            print("Max retry reached.")
        print(response.text)
        return response.json()


    def post_compair(self,source_path,compair_path):
        headers = {
            "accept": "text/plain",
            "Content-Type": "application/json-patch+json"
        }
        req_body = {"sourcePath":source_path,"comparePath":compair_path}
        print(req_body)
        retry_num = 1
        while retry_num <= 10:
            try:
                response = requests.get(f"{DMS_URL}/sysIntegrating/aiIntegrating/fileContent/generateWordRevisionFile",
                                        headers=headers,
                                        params=req_body)
                break
            except Exception as e:
                print(f"An unexpected error occurred: {e}")
                retry_num += 1
        if retry_num > 10:
            print("Max retry reached.")
        print(response.text)
        return response.json()

    # 第二版编辑接口
    def post_edit_file_v2(self, edit_json: dict):
        headers = {
            "accept": "text/plain",
            "Content-Type": "application/json-patch+json"
        }
        retry_num = 1
        while retry_num <= 10:
            try:
                response = requests.post(f"{DMS_URL}/sysIntegrating/aiIntegrating/fileContent/wordEditNew",
                                         headers=headers, json=edit_json)
                break
            except Exception as e:
                print(f"An unexpected error occurred: {e}")
                retry_num += 1
        if retry_num > 10:
            print("Max retry reached.")
        print(response.text)
        return response.json()

    def get_permissions_files(self, user_id: str, kgs: []):
        headers = {
            "accept": "text/plain"
        }
        params = {
            "UserId": user_id,
            "RootFileIdList": kgs
        }
        retry_num = 1
        while retry_num <= 10:
            try:
                response = requests.get(f"{DMS_URL}/integrate/aiIntegrating/userKnowledgeFiles",
                                        headers=headers,
                                        params=params)
                break
            except Exception as e:
                print(f"An unexpected error occurred: {e}")
                retry_num += 1
        if retry_num > 10:
            print("Max retry reached.")
        # print(response.text)
        return response.json()["data"]

    def post_errortodms(self, errorinfo: dict):
        headers = {
            "accept": "text/plain",
            "Content-Type": "application/json-patch+json"
        }
        retry_num = 1
        while retry_num <= 10:
            try:
                response = requests.post(f"{DMS_URL}/integrate/aiIntegrating/taskFailed",
                                         headers=headers,
                                         json=errorinfo)
                break
            except Exception as e:
                print(f"An unexpected error occurred: {e}")
                retry_num += 1
        if retry_num > 10:
            print("Max retry reached.")
        print(response.text)
        return response.json()


dmsoperator = DMSOperator()

if __name__ == "__main__":
    import json
    file_pubinfo = dmsoperator.get_permissions_files("b5de2470-13ee-4f97-a1e7-91d0b6369b42", ["eb3a0b16-bec5-4860-b47c-04f328ea0767"])
    print(file_pubinfo)
    file_pubinfo_json = json.dumps(file_pubinfo, indent=4, ensure_ascii=False)
    # 保存修改的json文件
    edit_SOPjsonfile_path = f"权限.json"
    with open(edit_SOPjsonfile_path, "w", encoding="utf-8") as f:
        f.write(file_pubinfo_json)
